import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader } from '../components/UI/Card';
import { Badge } from '../components/UI/Badge';
import { Button } from '../components/UI/Button';
import { Modal } from '../components/UI/Modal';
import { ConfirmDialog } from '../components/UI/ConfirmDialog';
import { MapModal } from '../components/Map/MapModal';
import { ToastContainer } from '../components/UI/Toast';
import { useToast } from '../hooks/useToast';
import { mockApi } from '../services/mockApi';
import { Vehicle, Route } from '../types';
import { 
  Truck,
  MapPin,
  Navigation,
  Fuel,
  Settings,
  Eye,
  Plus,
  Filter,
  Search,
  Activity,
  AlertTriangle,
  CheckCircle,
  Clock,
  Edit,
  Trash2,
  Save,
  X,
  User,
  Phone,
  Calendar,
  Gauge,
  Package
} from 'lucide-react';

const statusConfig = {
  available: { label: '空闲', variant: 'success' as const, icon: CheckCircle },
  in_use: { label: '使用中', variant: 'primary' as const, icon: Activity },
  maintenance: { label: '维护中', variant: 'warning' as const, icon: Settings },
  offline: { label: '离线', variant: 'error' as const, icon: AlertTriangle },
};

interface VehicleForm {
  plateNumber: string;
  type: string;
  capacity: number;
  status: Vehicle['status'];
  driverName: string;
  driverPhone: string;
  fuelConsumption: number;
  mileage: number;
  location: {
    address: string;
  };
}

interface RouteForm {
  name: string;
  origin: string;
  destination: string;
  distance: number;
  estimatedTime: number;
  vehicleTypes: string[];
  isActive: boolean;
  description?: string;
  waypoints: Array<{
    name: string;
    lat: number;
    lng: number;
  }>;
  transportMode: 'driving' | 'walking' | 'transit';
}

interface AdvancedVehicleFilters {
  capacityRange: {
    min: string;
    max: string;
  };
  fuelConsumptionRange: {
    min: string;
    max: string;
  };
  mileageRange: {
    min: string;
    max: string;
  };
  vehicleTypes: string[];
  lastMaintenanceRange: {
    start: string;
    end: string;
  };
}

export const Transport: React.FC = () => {
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [routes, setRoutes] = useState<Route[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'vehicles' | 'routes'>('vehicles');
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('');

  // 车辆相关状态
  const [selectedVehicle, setSelectedVehicle] = useState<Vehicle | null>(null);
  const [editingVehicle, setEditingVehicle] = useState<Vehicle | null>(null);
  const [showVehicleModal, setShowVehicleModal] = useState(false);
  const [showCreateVehicleModal, setShowCreateVehicleModal] = useState(false);
  const [showEditVehicleModal, setShowEditVehicleModal] = useState(false);
  const [showAdvancedVehicleFilter, setShowAdvancedVehicleFilter] = useState(false);
  const [vehicleForm, setVehicleForm] = useState<VehicleForm>({
    plateNumber: '',
    type: '',
    capacity: 0,
    status: 'available',
    driverName: '',
    driverPhone: '',
    fuelConsumption: 0,
    mileage: 0,
    location: {
      address: ''
    }
  });
  const [vehicleLoading, setVehicleLoading] = useState(false);

  // 路线相关状态
  const [selectedRoute, setSelectedRoute] = useState<Route | null>(null);
  const [editingRoute, setEditingRoute] = useState<Route | null>(null);
  const [showRouteModal, setShowRouteModal] = useState(false);
  const [showCreateRouteModal, setShowCreateRouteModal] = useState(false);
  const [showEditRouteModal, setShowEditRouteModal] = useState(false);
  const [routeForm, setRouteForm] = useState<RouteForm>({
    name: '',
    origin: '',
    destination: '',
    distance: 0,
    estimatedTime: 0,
    vehicleTypes: [],
    isActive: true,
    description: '',
    waypoints: [],
    transportMode: 'driving'
  });
  const [routeLoading, setRouteLoading] = useState(false);

  // 删除确认对话框
  const [deleteConfirm, setDeleteConfirm] = useState<{
    isOpen: boolean;
    type: 'vehicle' | 'route';
    item: Vehicle | Route | null;
    loading: boolean;
  }>({
    isOpen: false,
    type: 'vehicle',
    item: null,
    loading: false
  });

  // 地图模态框
  const [showMapModal, setShowMapModal] = useState(false);

  // 高级筛选
  const [advancedVehicleFilters, setAdvancedVehicleFilters] = useState<AdvancedVehicleFilters>({
    capacityRange: { min: '', max: '' },
    fuelConsumptionRange: { min: '', max: '' },
    mileageRange: { min: '', max: '' },
    vehicleTypes: [],
    lastMaintenanceRange: { start: '', end: '' }
  });
  const [activeVehicleFiltersCount, setActiveVehicleFiltersCount] = useState(0);

  const { toasts, removeToast, success, error, warning } = useToast();

  useEffect(() => {
    fetchData();
  }, []);

  // 计算活跃筛选器数量
  useEffect(() => {
    let count = 0;
    if (advancedVehicleFilters.capacityRange.min || advancedVehicleFilters.capacityRange.max) count++;
    if (advancedVehicleFilters.fuelConsumptionRange.min || advancedVehicleFilters.fuelConsumptionRange.max) count++;
    if (advancedVehicleFilters.mileageRange.min || advancedVehicleFilters.mileageRange.max) count++;
    if (advancedVehicleFilters.vehicleTypes.length > 0) count++;
    if (advancedVehicleFilters.lastMaintenanceRange.start || advancedVehicleFilters.lastMaintenanceRange.end) count++;
    setActiveVehicleFiltersCount(count);
  }, [advancedVehicleFilters]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const [vehiclesData, routesData] = await Promise.all([
        mockApi.getVehicles(),
        mockApi.getRoutes()
      ]);
      setVehicles(vehiclesData);
      setRoutes(routesData);
    } catch (error) {
      console.error('Failed to fetch transport data:', error);
      error('获取数据失败', '请检查网络连接后重试');
    } finally {
      setLoading(false);
    }
  };

  // 车辆相关处理函数
  const handleViewVehicle = (vehicle: Vehicle) => {
    setSelectedVehicle(vehicle);
    setShowVehicleModal(true);
  };

  const handleCreateVehicle = () => {
    setVehicleForm({
      plateNumber: '',
      type: '',
      capacity: 0,
      status: 'available',
      driverName: '',
      driverPhone: '',
      fuelConsumption: 0,
      mileage: 0,
      location: {
        address: ''
      }
    });
    setShowCreateVehicleModal(true);
  };

  const handleEditVehicle = (vehicle: Vehicle) => {
    setEditingVehicle(vehicle);
    setVehicleForm({
      plateNumber: vehicle.plateNumber,
      type: vehicle.type,
      capacity: vehicle.capacity,
      status: vehicle.status,
      driverName: vehicle.driverName,
      driverPhone: vehicle.driverPhone,
      fuelConsumption: vehicle.fuelConsumption,
      mileage: vehicle.mileage,
      location: {
        address: vehicle.location.address
      }
    });
    setShowEditVehicleModal(true);
  };

  const handleSaveVehicle = async (isEdit: boolean = false) => {
    if (!vehicleForm.plateNumber || !vehicleForm.type || !vehicleForm.driverName) {
      warning('请填写必填字段', '车牌号、车辆类型和司机姓名为必填项');
      return;
    }

    setVehicleLoading(true);
    try {
      if (isEdit && editingVehicle) {
        const updatedVehicle = await mockApi.updateVehicle(editingVehicle.id, {
          ...vehicleForm,
          location: {
            ...editingVehicle.location,
            address: vehicleForm.location.address
          }
        });

        if (updatedVehicle) {
          setVehicles(prevVehicles => 
            prevVehicles.map(vehicle => 
              vehicle.id === editingVehicle.id ? updatedVehicle : vehicle
            )
          );
          setShowEditVehicleModal(false);
          setEditingVehicle(null);
          success('车辆更新成功', '车辆信息已成功更新');
        }
      } else {
        const newVehicle = await mockApi.createVehicle({
          ...vehicleForm,
          location: {
            lat: 39.9042 + (Math.random() - 0.5) * 0.5,
            lng: 116.4074 + (Math.random() - 0.5) * 0.5,
            address: vehicleForm.location.address || '北京市朝阳区'
          },
          driverId: `DRV-${Date.now()}`,
          lastMaintenance: new Date().toISOString()
        });

        setVehicles(prevVehicles => [newVehicle, ...prevVehicles]);
        setShowCreateVehicleModal(false);
        success('车辆创建成功', '新车辆已成功添加到系统');
      }
    } catch (err) {
      console.error('Failed to save vehicle:', err);
      error('保存失败', '车辆信息保存失败，请重试');
    } finally {
      setVehicleLoading(false);
    }
  };

  const handleDeleteVehicle = (vehicle: Vehicle) => {
    setDeleteConfirm({
      isOpen: true,
      type: 'vehicle',
      item: vehicle,
      loading: false
    });
  };

  // 路线相关处理函数
  const handleViewRoute = (route: Route) => {
    setSelectedRoute(route);
    setShowRouteModal(true);
  };

  const handleCreateRoute = () => {
    setRouteForm({
      name: '',
      origin: '',
      destination: '',
      distance: 0,
      estimatedTime: 0,
      vehicleTypes: [],
      isActive: true,
      description: '',
      waypoints: [],
      transportMode: 'driving'
    });
    setShowCreateRouteModal(true);
  };

  const handleEditRoute = (route: Route) => {
    setEditingRoute(route);
    setRouteForm({
      name: route.name,
      origin: route.origin,
      destination: route.destination,
      distance: route.distance,
      estimatedTime: route.estimatedTime,
      vehicleTypes: route.vehicleTypes,
      isActive: route.isActive,
      description: '',
      waypoints: route.waypoints,
      transportMode: 'driving'
    });
    setShowEditRouteModal(true);
  };

  const handleSaveRoute = async (isEdit: boolean = false) => {
    if (!routeForm.name || !routeForm.origin || !routeForm.destination) {
      warning('请填写必填字段', '路线名称、起点和终点为必填项');
      return;
    }

    setRouteLoading(true);
    try {
      if (isEdit && editingRoute) {
        const updatedRoute = await mockApi.updateRoute(editingRoute.id, {
          ...routeForm,
          createdAt: editingRoute.createdAt
        });

        if (updatedRoute) {
          setRoutes(prevRoutes => 
            prevRoutes.map(route => 
              route.id === editingRoute.id ? updatedRoute : route
            )
          );
          setShowEditRouteModal(false);
          setEditingRoute(null);
          success('路线更新成功', '路线信息已成功更新');
        }
      } else {
        const newRoute = await mockApi.createRoute({
          ...routeForm,
          createdAt: new Date().toISOString()
        });

        setRoutes(prevRoutes => [newRoute, ...prevRoutes]);
        setShowCreateRouteModal(false);
        success('路线创建成功', '新路线已成功添加到系统');
      }
    } catch (err) {
      console.error('Failed to save route:', err);
      error('保存失败', '路线信息保存失败，请重试');
    } finally {
      setRouteLoading(false);
    }
  };

  const handleDeleteRoute = (route: Route) => {
    setDeleteConfirm({
      isOpen: true,
      type: 'route',
      item: route,
      loading: false
    });
  };

  // 删除确认处理
  const handleConfirmDelete = async () => {
    if (!deleteConfirm.item) return;

    setDeleteConfirm(prev => ({ ...prev, loading: true }));

    try {
      if (deleteConfirm.type === 'vehicle') {
        const success_result = await mockApi.deleteVehicle(deleteConfirm.item.id);
        if (success_result) {
          setVehicles(prevVehicles => 
            prevVehicles.filter(vehicle => vehicle.id !== deleteConfirm.item!.id)
          );
          success('删除成功', '车辆已成功删除');
        } else {
          error('删除失败', '车辆删除失败，请重试');
        }
      } else {
        const success_result = await mockApi.deleteRoute(deleteConfirm.item.id);
        if (success_result) {
          setRoutes(prevRoutes => 
            prevRoutes.filter(route => route.id !== deleteConfirm.item!.id)
          );
          success('删除成功', '路线已成功删除');
        } else {
          error('删除失败', '路线删除失败，请重试');
        }
      }
    } catch (err) {
      console.error('Failed to delete:', err);
      error('删除失败', '删除操作失败，请重试');
    } finally {
      setDeleteConfirm({
        isOpen: false,
        type: 'vehicle',
        item: null,
        loading: false
      });
    }
  };

  // 高级筛选处理
  const handleAdvancedVehicleFilterChange = (key: keyof AdvancedVehicleFilters, value: any) => {
    setAdvancedVehicleFilters(prev => ({
      ...prev,
      [key]: value
    }));
  };

  const handleVehicleTypeToggle = (vehicleType: string) => {
    setAdvancedVehicleFilters(prev => ({
      ...prev,
      vehicleTypes: prev.vehicleTypes.includes(vehicleType)
        ? prev.vehicleTypes.filter(type => type !== vehicleType)
        : [...prev.vehicleTypes, vehicleType]
    }));
  };

  const resetAdvancedVehicleFilters = () => {
    setAdvancedVehicleFilters({
      capacityRange: { min: '', max: '' },
      fuelConsumptionRange: { min: '', max: '' },
      mileageRange: { min: '', max: '' },
      vehicleTypes: [],
      lastMaintenanceRange: { start: '', end: '' }
    });
  };

  const applyAdvancedVehicleFilters = () => {
    console.log('应用高级筛选:', advancedVehicleFilters);
    setShowAdvancedVehicleFilter(false);
  };

  // 筛选逻辑
  const filteredVehicles = vehicles.filter(vehicle => {
    const matchesSearch = vehicle.plateNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         vehicle.driverName.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = !statusFilter || vehicle.status === statusFilter;

    if (!matchesSearch || !matchesStatus) return false;

    // 高级筛选
    if (advancedVehicleFilters.capacityRange.min && vehicle.capacity < parseInt(advancedVehicleFilters.capacityRange.min)) return false;
    if (advancedVehicleFilters.capacityRange.max && vehicle.capacity > parseInt(advancedVehicleFilters.capacityRange.max)) return false;
    if (advancedVehicleFilters.fuelConsumptionRange.min && vehicle.fuelConsumption < parseInt(advancedVehicleFilters.fuelConsumptionRange.min)) return false;
    if (advancedVehicleFilters.fuelConsumptionRange.max && vehicle.fuelConsumption > parseInt(advancedVehicleFilters.fuelConsumptionRange.max)) return false;
    if (advancedVehicleFilters.mileageRange.min && vehicle.mileage < parseInt(advancedVehicleFilters.mileageRange.min)) return false;
    if (advancedVehicleFilters.mileageRange.max && vehicle.mileage > parseInt(advancedVehicleFilters.mileageRange.max)) return false;
    if (advancedVehicleFilters.vehicleTypes.length > 0 && !advancedVehicleFilters.vehicleTypes.includes(vehicle.type)) return false;

    return true;
  });

  const filteredRoutes = routes.filter(route =>
    route.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    route.origin.toLowerCase().includes(searchTerm.toLowerCase()) ||
    route.destination.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const vehicleStats = {
    total: vehicles.length,
    available: vehicles.filter(v => v.status === 'available').length,
    inUse: vehicles.filter(v => v.status === 'in_use').length,
    maintenance: vehicles.filter(v => v.status === 'maintenance').length,
  };

  const vehicleTypeOptions = ['小型货车', '中型货车', '大型货车', '冷藏车', '危险品运输车'];
  const routeVehicleTypeOptions = ['小型货车', '中型货车', '大型货车', '冷藏车'];

  return (
    <div className="space-y-6 animate-slide-up">
      {/* Toast 通知 */}
      <ToastContainer toasts={toasts} onClose={removeToast} />

      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-800">货运管理</h1>
          <p className="text-gray-600">实时监控车辆状态和运输路线管理</p>
        </div>
        <div className="flex space-x-2">
          <Button 
            variant="outline" 
            icon={<MapPin className="w-4 h-4" />}
            onClick={() => setShowMapModal(true)}
          >
            地图视图
          </Button>
          <Button 
            icon={<Plus className="w-4 h-4" />}
            onClick={activeTab === 'vehicles' ? handleCreateVehicle : handleCreateRoute}
          >
            {activeTab === 'vehicles' ? '添加车辆' : '创建路线'}
          </Button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card hover className="bg-gradient-to-br from-primary-50 to-primary-100 border-primary-200">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-primary-700">总车辆数</p>
                <p className="text-2xl font-bold text-primary-800">{vehicleStats.total}</p>
              </div>
              <Truck className="w-8 h-8 text-primary-600" />
            </div>
          </CardContent>
        </Card>

        <Card hover className="bg-gradient-to-br from-success-50 to-success-100 border-success-200">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-success-700">可用车辆</p>
                <p className="text-2xl font-bold text-success-800">{vehicleStats.available}</p>
              </div>
              <CheckCircle className="w-8 h-8 text-success-600" />
            </div>
          </CardContent>
        </Card>

        <Card hover className="bg-gradient-to-br from-warning-50 to-warning-100 border-warning-200">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-warning-700">使用中</p>
                <p className="text-2xl font-bold text-warning-800">{vehicleStats.inUse}</p>
              </div>
              <Activity className="w-8 h-8 text-warning-600" />
            </div>
          </CardContent>
        </Card>

        <Card hover className="bg-gradient-to-br from-error-50 to-error-100 border-error-200">
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-error-700">维护中</p>
                <p className="text-2xl font-bold text-error-800">{vehicleStats.maintenance}</p>
              </div>
              <Settings className="w-8 h-8 text-error-600" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Tab Navigation */}
      <div className="border-b border-gray-200">
        <nav className="flex space-x-8">
          <button
            onClick={() => setActiveTab('vehicles')}
            className={`pb-4 px-1 border-b-2 font-medium text-sm transition-colors duration-200 ${
              activeTab === 'vehicles'
                ? 'border-primary-500 text-primary-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            车辆监控
          </button>
          <button
            onClick={() => setActiveTab('routes')}
            className={`pb-4 px-1 border-b-2 font-medium text-sm transition-colors duration-200 ${
              activeTab === 'routes'
                ? 'border-primary-500 text-primary-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            路线管理
          </button>
        </nav>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="p-6">
          <div className="flex flex-col lg:flex-row gap-4">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
              <input
                type="text"
                placeholder={activeTab === 'vehicles' ? '搜索车牌号、司机姓名...' : '搜索路线名称、起止地点...'}
                className="w-full pl-10 pr-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            {activeTab === 'vehicles' && (
              <div className="flex gap-2">
                <select
                  className="px-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                >
                  <option value="">全部状态</option>
                  {Object.entries(statusConfig).map(([key, config]) => (
                    <option key={key} value={key}>{config.label}</option>
                  ))}
                </select>
                <Button 
                  variant="outline" 
                  icon={<Filter className="w-4 h-4" />}
                  onClick={() => setShowAdvancedVehicleFilter(true)}
                  className="relative"
                >
                  更多筛选
                  {activeVehicleFiltersCount > 0 && (
                    <span className="absolute -top-2 -right-2 w-5 h-5 bg-primary-500 text-white text-xs rounded-full flex items-center justify-center">
                      {activeVehicleFiltersCount}
                    </span>
                  )}
                </Button>
              </div>
            )}
          </div>

          {/* 活跃筛选器显示 */}
          {activeTab === 'vehicles' && activeVehicleFiltersCount > 0 && (
            <div className="mt-4 flex flex-wrap gap-2">
              <span className="text-sm text-gray-600">已应用筛选器:</span>
              {advancedVehicleFilters.capacityRange.min && (
                <Badge variant="primary" size="sm">
                  最小载重: {advancedVehicleFilters.capacityRange.min}吨
                </Badge>
              )}
              {advancedVehicleFilters.capacityRange.max && (
                <Badge variant="primary" size="sm">
                  最大载重: {advancedVehicleFilters.capacityRange.max}吨
                </Badge>
              )}
              {advancedVehicleFilters.vehicleTypes.map(type => (
                <Badge key={type} variant="secondary" size="sm">
                  {type}
                </Badge>
              ))}
              <Button
                variant="ghost"
                size="sm"
                icon={<X className="w-3 h-3" />}
                onClick={resetAdvancedVehicleFilters}
                className="text-xs"
              >
                清除筛选
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Content */}
      {activeTab === 'vehicles' ? (
        // Vehicles List
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold text-gray-800">车辆列表</h2>
              <Badge variant="info">{filteredVehicles.length} 辆车</Badge>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            {loading ? (
              <div className="p-6">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {Array.from({ length: 6 }).map((_, i) => (
                    <div key={i} className="p-4 border border-gray-200 rounded-xl animate-pulse">
                      <div className="h-6 bg-gray-200 rounded mb-4"></div>
                      <div className="space-y-2">
                        <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                        <div className="h-4 bg-gray-200 rounded w-1/2"></div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ) : (
              <div className="p-6">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {filteredVehicles.map((vehicle) => {
                    const statusInfo = statusConfig[vehicle.status];
                    const StatusIcon = statusInfo.icon;
                    
                    return (
                      <Card key={vehicle.id} hover gradient className="relative overflow-hidden">
                        <CardContent className="p-6">
                          <div className="flex items-start justify-between mb-4">
                            <div>
                              <h3 className="text-lg font-semibold text-gray-800 mb-1">
                                {vehicle.plateNumber}
                              </h3>
                              <Badge variant={statusInfo.variant} size="sm">
                                <StatusIcon className="w-3 h-3 mr-1" />
                                {statusInfo.label}
                              </Badge>
                            </div>
                            <div className="w-12 h-12 bg-gradient-to-br from-primary-100 to-secondary-100 rounded-xl flex items-center justify-center">
                              <Truck className="w-6 h-6 text-primary-600" />
                            </div>
                          </div>

                          <div className="space-y-3">
                            <div className="flex items-center justify-between text-sm">
                              <span className="text-gray-600">车辆类型</span>
                              <span className="font-medium text-gray-800">{vehicle.type}</span>
                            </div>
                            <div className="flex items-center justify-between text-sm">
                              <span className="text-gray-600">载重量</span>
                              <span className="font-medium text-gray-800">{vehicle.capacity}吨</span>
                            </div>
                            <div className="flex items-center justify-between text-sm">
                              <span className="text-gray-600">司机</span>
                              <span className="font-medium text-gray-800">{vehicle.driverName}</span>
                            </div>
                            <div className="flex items-center text-sm text-gray-600">
                              <MapPin className="w-4 h-4 mr-1" />
                              <span className="truncate">{vehicle.location.address}</span>
                            </div>
                          </div>

                          <div className="flex items-center justify-between mt-6 pt-4 border-t border-gray-100">
                            <div className="flex items-center space-x-1 text-sm text-gray-600">
                              <Fuel className="w-4 h-4" />
                              <span>{vehicle.fuelConsumption}L/100km</span>
                            </div>
                            <div className="flex items-center space-x-2">
                              <Button 
                                variant="ghost" 
                                size="sm" 
                                icon={<Eye className="w-4 h-4" />}
                                onClick={() => handleViewVehicle(vehicle)}
                              >
                                详情
                              </Button>
                              <Button 
                                variant="ghost" 
                                size="sm" 
                                icon={<Edit className="w-4 h-4" />}
                                onClick={() => handleEditVehicle(vehicle)}
                              >
                                编辑
                              </Button>
                              <Button 
                                variant="ghost" 
                                size="sm" 
                                icon={<Trash2 className="w-4 h-4" />}
                                onClick={() => handleDeleteVehicle(vehicle)}
                              >
                                删除
                              </Button>
                            </div>
                          </div>

                          {/* Status indicator dot */}
                          <div className="absolute top-4 right-4">
                            <div className={`w-3 h-3 rounded-full ${
                              vehicle.status === 'available' ? 'bg-success-500' :
                              vehicle.status === 'in_use' ? 'bg-primary-500' :
                              vehicle.status === 'maintenance' ? 'bg-warning-500' :
                              'bg-error-500'
                            } animate-pulse`}></div>
                          </div>
                        </CardContent>
                      </Card>
                    );
                  })}
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      ) : (
        // Routes List
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold text-gray-800">运输路线</h2>
              <Badge variant="info">{filteredRoutes.length} 条路线</Badge>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            <div className="divide-y divide-gray-100">
              {filteredRoutes.map((route) => (
                <div key={route.id} className="p-6 hover:bg-gray-50 transition-colors duration-200">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-4">
                      <div className="w-12 h-12 bg-gradient-to-br from-secondary-100 to-accent-100 rounded-xl flex items-center justify-center">
                        <Navigation className="w-6 h-6 text-secondary-600" />
                      </div>
                      <div>
                        <div className="flex items-center space-x-2 mb-1">
                          <h3 className="font-semibold text-gray-800">{route.name}</h3>
                          <Badge variant={route.isActive ? 'success' : 'error'} size="sm">
                            {route.isActive ? '活跃' : '停用'}
                          </Badge>
                        </div>
                        <div className="flex items-center space-x-4 text-sm text-gray-600">
                          <div className="flex items-center space-x-1">
                            <MapPin className="w-4 h-4" />
                            <span>{route.origin} → {route.destination}</span>
                          </div>
                          <div className="flex items-center space-x-1">
                            <Clock className="w-4 h-4" />
                            <span>{route.estimatedTime}小时</span>
                          </div>
                          <span>{route.distance}公里</span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center space-x-4">
                      <div className="text-right">
                        <p className="text-sm text-gray-600">适用车型</p>
                        <p className="font-medium text-gray-800">{route.vehicleTypes.join(', ')}</p>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Button 
                          variant="ghost" 
                          size="sm" 
                          icon={<Eye className="w-4 h-4" />}
                          onClick={() => handleViewRoute(route)}
                        >
                          查看
                        </Button>
                        <Button 
                          variant="ghost" 
                          size="sm" 
                          icon={<Edit className="w-4 h-4" />}
                          onClick={() => handleEditRoute(route)}
                        >
                          编辑
                        </Button>
                        <Button 
                          variant="ghost" 
                          size="sm" 
                          icon={<Trash2 className="w-4 h-4" />}
                          onClick={() => handleDeleteRoute(route)}
                        >
                          删除
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 地图模态框 */}
      <MapModal
        isOpen={showMapModal}
        onClose={() => setShowMapModal(false)}
        vehicles={vehicles}
        routes={routes}
        onVehicleClick={handleViewVehicle}
        onRouteClick={handleViewRoute}
      />

      {/* 车辆高级筛选模态框 */}
      <Modal
        isOpen={showAdvancedVehicleFilter}
        onClose={() => setShowAdvancedVehicleFilter(false)}
        title="车辆高级筛选"
        size="lg"
      >
        <div className="space-y-6">
          {/* 载重范围 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">载重范围 (吨)</label>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-xs text-gray-500 mb-1">最小载重</label>
                <input
                  type="number"
                  placeholder="0"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  value={advancedVehicleFilters.capacityRange.min}
                  onChange={(e) => handleAdvancedVehicleFilterChange('capacityRange', {
                    ...advancedVehicleFilters.capacityRange,
                    min: e.target.value
                  })}
                />
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">最大载重</label>
                <input
                  type="number"
                  placeholder="无限制"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  value={advancedVehicleFilters.capacityRange.max}
                  onChange={(e) => handleAdvancedVehicleFilterChange('capacityRange', {
                    ...advancedVehicleFilters.capacityRange,
                    max: e.target.value
                  })}
                />
              </div>
            </div>
          </div>

          {/* 油耗范围 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">油耗范围 (L/100km)</label>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-xs text-gray-500 mb-1">最低油耗</label>
                <input
                  type="number"
                  placeholder="0"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  value={advancedVehicleFilters.fuelConsumptionRange.min}
                  onChange={(e) => handleAdvancedVehicleFilterChange('fuelConsumptionRange', {
                    ...advancedVehicleFilters.fuelConsumptionRange,
                    min: e.target.value
                  })}
                />
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">最高油耗</label>
                <input
                  type="number"
                  placeholder="无限制"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  value={advancedVehicleFilters.fuelConsumptionRange.max}
                  onChange={(e) => handleAdvancedVehicleFilterChange('fuelConsumptionRange', {
                    ...advancedVehicleFilters.fuelConsumptionRange,
                    max: e.target.value
                  })}
                />
              </div>
            </div>
          </div>

          {/* 里程范围 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">里程范围 (km)</label>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-xs text-gray-500 mb-1">最低里程</label>
                <input
                  type="number"
                  placeholder="0"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  value={advancedVehicleFilters.mileageRange.min}
                  onChange={(e) => handleAdvancedVehicleFilterChange('mileageRange', {
                    ...advancedVehicleFilters.mileageRange,
                    min: e.target.value
                  })}
                />
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">最高里程</label>
                <input
                  type="number"
                  placeholder="无限制"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                  value={advancedVehicleFilters.mileageRange.max}
                  onChange={(e) => handleAdvancedVehicleFilterChange('mileageRange', {
                    ...advancedVehicleFilters.mileageRange,
                    max: e.target.value
                  })}
                />
              </div>
            </div>
          </div>

          {/* 车辆类型 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-3">车辆类型</label>
            <div className="grid grid-cols-3 gap-2">
              {vehicleTypeOptions.map(type => (
                <label key={type} className="flex items-center space-x-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={advancedVehicleFilters.vehicleTypes.includes(type)}
                    onChange={() => handleVehicleTypeToggle(type)}
                    className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                  />
                  <span className="text-sm text-gray-700">{type}</span>
                </label>
              ))}
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="flex justify-between pt-4 border-t border-gray-200">
            <Button
              variant="outline"
              icon={<X className="w-4 h-4" />}
              onClick={resetAdvancedVehicleFilters}
            >
              重置筛选
            </Button>
            <div className="flex space-x-3">
              <Button
                variant="outline"
                onClick={() => setShowAdvancedVehicleFilter(false)}
              >
                取消
              </Button>
              <Button
                icon={<Filter className="w-4 h-4" />}
                onClick={applyAdvancedVehicleFilters}
              >
                应用筛选 ({activeVehicleFiltersCount})
              </Button>
            </div>
          </div>
        </div>
      </Modal>

      {/* 车辆详情模态框 */}
      <Modal
        isOpen={showVehicleModal}
        onClose={() => setShowVehicleModal(false)}
        title="车辆详情"
        size="lg"
      >
        {selectedVehicle && (
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-gray-600">车牌号</label>
                  <p className="text-lg font-semibold text-gray-800">{selectedVehicle.plateNumber}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">车辆类型</label>
                  <p className="text-gray-800">{selectedVehicle.type}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">载重量</label>
                  <p className="text-gray-800">{selectedVehicle.capacity}吨</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">状态</label>
                  <div className="mt-1">
                    <Badge variant={statusConfig[selectedVehicle.status].variant}>
                      {statusConfig[selectedVehicle.status].label}
                    </Badge>
                  </div>
                </div>
              </div>
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-gray-600">司机信息</label>
                  <div className="space-y-1">
                    <div className="flex items-center space-x-2">
                      <User className="w-4 h-4 text-gray-500" />
                      <span className="text-gray-800">{selectedVehicle.driverName}</span>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Phone className="w-4 h-4 text-gray-500" />
                      <span className="text-gray-800">{selectedVehicle.driverPhone}</span>
                    </div>
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">车辆性能</label>
                  <div className="space-y-1">
                    <div className="flex items-center space-x-2">
                      <Fuel className="w-4 h-4 text-gray-500" />
                      <span className="text-gray-800">{selectedVehicle.fuelConsumption}L/100km</span>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Gauge className="w-4 h-4 text-gray-500" />
                      <span className="text-gray-800">{selectedVehicle.mileage.toLocaleString()}km</span>
                    </div>
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">当前位置</label>
                  <div className="flex items-center space-x-2">
                    <MapPin className="w-4 h-4 text-gray-500" />
                    <span className="text-gray-800">{selectedVehicle.location.address}</span>
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">上次保养</label>
                  <div className="flex items-center space-x-2">
                    <Calendar className="w-4 h-4 text-gray-500" />
                    <span className="text-gray-800">
                      {new Date(selectedVehicle.lastMaintenance).toLocaleDateString('zh-CN')}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}
      </Modal>

      {/* 创建车辆模态框 */}
      <Modal
        isOpen={showCreateVehicleModal}
        onClose={() => setShowCreateVehicleModal(false)}
        title="添加车辆"
        size="lg"
      >
        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">车牌号 *</label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="请输入车牌号"
                value={vehicleForm.plateNumber}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, plateNumber: e.target.value }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">车辆类型 *</label>
              <select 
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={vehicleForm.type}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, type: e.target.value }))}
              >
                <option value="">请选择车辆类型</option>
                {vehicleTypeOptions.map(type => (
                  <option key={type} value={type}>{type}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">载重量(吨)</label>
              <input
                type="number"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="载重量"
                value={vehicleForm.capacity}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, capacity: Number(e.target.value) }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">车辆状态</label>
              <select 
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={vehicleForm.status}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, status: e.target.value as Vehicle['status'] }))}
              >
                {Object.entries(statusConfig).map(([key, config]) => (
                  <option key={key} value={key}>{config.label}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">司机姓名 *</label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="请输入司机姓名"
                value={vehicleForm.driverName}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, driverName: e.target.value }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">司机电话</label>
              <input
                type="tel"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="请输入司机电话"
                value={vehicleForm.driverPhone}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, driverPhone: e.target.value }))}
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">油耗(L/100km)</label>
              <input
                type="number"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="油耗"
                value={vehicleForm.fuelConsumption}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, fuelConsumption: Number(e.target.value) }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">里程(km)</label>
              <input
                type="number"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="里程"
                value={vehicleForm.mileage}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, mileage: Number(e.target.value) }))}
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">当前位置</label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              placeholder="请输入当前位置"
              value={vehicleForm.location.address}
              onChange={(e) => setVehicleForm(prev => ({ 
                ...prev, 
                location: { ...prev.location, address: e.target.value }
              }))}
            />
          </div>

          <div className="flex justify-end space-x-3 pt-4">
            <Button variant="outline" onClick={() => setShowCreateVehicleModal(false)}>
              取消
            </Button>
            <Button 
              icon={<Save className="w-4 h-4" />}
              onClick={() => handleSaveVehicle(false)}
              loading={vehicleLoading}
            >
              添加车辆
            </Button>
          </div>
        </div>
      </Modal>

      {/* 编辑车辆模态框 */}
      <Modal
        isOpen={showEditVehicleModal}
        onClose={() => setShowEditVehicleModal(false)}
        title="编辑车辆"
        size="lg"
      >
        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">车牌号 *</label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="请输入车牌号"
                value={vehicleForm.plateNumber}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, plateNumber: e.target.value }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">车辆类型 *</label>
              <select 
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={vehicleForm.type}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, type: e.target.value }))}
              >
                <option value="">请选择车辆类型</option>
                {vehicleTypeOptions.map(type => (
                  <option key={type} value={type}>{type}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">载重量(吨)</label>
              <input
                type="number"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="载重量"
                value={vehicleForm.capacity}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, capacity: Number(e.target.value) }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">车辆状态</label>
              <select 
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={vehicleForm.status}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, status: e.target.value as Vehicle['status'] }))}
              >
                {Object.entries(statusConfig).map(([key, config]) => (
                  <option key={key} value={key}>{config.label}</option>
                ))}
              </select>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">司机姓名 *</label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="请输入司机姓名"
                value={vehicleForm.driverName}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, driverName: e.target.value }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">司机电话</label>
              <input
                type="tel"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="请输入司机电话"
                value={vehicleForm.driverPhone}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, driverPhone: e.target.value }))}
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">油耗(L/100km)</label>
              <input
                type="number"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="油耗"
                value={vehicleForm.fuelConsumption}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, fuelConsumption: Number(e.target.value) }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">里程(km)</label>
              <input
                type="number"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="里程"
                value={vehicleForm.mileage}
                onChange={(e) => setVehicleForm(prev => ({ ...prev, mileage: Number(e.target.value) }))}
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">当前位置</label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              placeholder="请输入当前位置"
              value={vehicleForm.location.address}
              onChange={(e) => setVehicleForm(prev => ({ 
                ...prev, 
                location: { ...prev.location, address: e.target.value }
              }))}
            />
          </div>

          <div className="flex justify-end space-x-3 pt-4">
            <Button variant="outline" onClick={() => setShowEditVehicleModal(false)}>
              取消
            </Button>
            <Button 
              icon={<Save className="w-4 h-4" />}
              onClick={() => handleSaveVehicle(true)}
              loading={vehicleLoading}
            >
              保存修改
            </Button>
          </div>
        </div>
      </Modal>

      {/* 路线详情模态框 */}
      <Modal
        isOpen={showRouteModal}
        onClose={() => setShowRouteModal(false)}
        title="路线详情"
        size="lg"
      >
        {selectedRoute && (
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-gray-600">路线名称</label>
                  <p className="text-lg font-semibold text-gray-800">{selectedRoute.name}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">运输路线</label>
                  <div className="flex items-center space-x-2 text-gray-800">
                    <span>{selectedRoute.origin}</span>
                    <span>→</span>
                    <span>{selectedRoute.destination}</span>
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">路线状态</label>
                  <div className="mt-1">
                    <Badge variant={selectedRoute.isActive ? 'success' : 'error'}>
                      {selectedRoute.isActive ? '活跃' : '停用'}
                    </Badge>
                  </div>
                </div>
              </div>
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium text-gray-600">距离</label>
                  <p className="text-gray-800">{selectedRoute.distance}公里</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">预计时间</label>
                  <p className="text-gray-800">{selectedRoute.estimatedTime}小时</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">适用车型</label>
                  <div className="flex flex-wrap gap-1 mt-1">
                    {selectedRoute.vehicleTypes.map((type, index) => (
                      <Badge key={index} variant="secondary" size="sm">
                        {type}
                      </Badge>
                    ))}
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-600">创建时间</label>
                  <p className="text-gray-800">
                    {new Date(selectedRoute.createdAt).toLocaleDateString('zh-CN')}
                  </p>
                </div>
              </div>
            </div>

            {selectedRoute.waypoints.length > 0 && (
              <div>
                <label className="text-sm font-medium text-gray-600 mb-3 block">途经点</label>
                <div className="space-y-2">
                  {selectedRoute.waypoints.map((waypoint, index) => (
                    <div key={index} className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                      <div className="w-6 h-6 bg-primary-500 text-white rounded-full flex items-center justify-center text-xs font-medium">
                        {index + 1}
                      </div>
                      <span className="text-gray-800">{waypoint.name}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}
      </Modal>

      {/* 创建路线模态框 */}
      <Modal
        isOpen={showCreateRouteModal}
        onClose={() => setShowCreateRouteModal(false)}
        title="创建路线"
        size="lg"
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">路线名称 *</label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              placeholder="请输入路线名称"
              value={routeForm.name}
              onChange={(e) => setRouteForm(prev => ({ ...prev, name: e.target.value }))}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">起点 *</label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="请输入起点"
                value={routeForm.origin}
                onChange={(e) => setRouteForm(prev => ({ ...prev, origin: e.target.value }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">终点 *</label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="请输入终点"
                value={routeForm.destination}
                onChange={(e) => setRouteForm(prev => ({ ...prev, destination: e.target.value }))}
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">距离(公里)</label>
              <input
                type="number"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="距离"
                value={routeForm.distance}
                onChange={(e) => setRouteForm(prev => ({ ...prev, distance: Number(e.target.value) }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">预计时间(小时)</label>
              <input
                type="number"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="预计时间"
                value={routeForm.estimatedTime}
                onChange={(e) => setRouteForm(prev => ({ ...prev, estimatedTime: Number(e.target.value) }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">交通方式</label>
              <select 
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={routeForm.transportMode}
                onChange={(e) => setRouteForm(prev => ({ ...prev, transportMode: e.target.value as any }))}
              >
                <option value="driving">🚗 驾车</option>
                <option value="walking">🚶 步行</option>
                <option value="transit">🚌 公交</option>
              </select>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">适用车型</label>
            <div className="grid grid-cols-2 gap-2">
              {routeVehicleTypeOptions.map(type => (
                <label key={type} className="flex items-center space-x-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={routeForm.vehicleTypes.includes(type)}
                    onChange={(e) => {
                      if (e.target.checked) {
                        setRouteForm(prev => ({ 
                          ...prev, 
                          vehicleTypes: [...prev.vehicleTypes, type] 
                        }));
                      } else {
                        setRouteForm(prev => ({ 
                          ...prev, 
                          vehicleTypes: prev.vehicleTypes.filter(t => t !== type) 
                        }));
                      }
                    }}
                    className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                  />
                  <span className="text-sm text-gray-700">{type}</span>
                </label>
              ))}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">路线描述</label>
            <textarea
              rows={3}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              placeholder="请输入路线描述（可选）"
              value={routeForm.description}
              onChange={(e) => setRouteForm(prev => ({ ...prev, description: e.target.value }))}
            />
          </div>

          <div className="flex items-center space-x-2">
            <input
              type="checkbox"
              id="isActive"
              checked={routeForm.isActive}
              onChange={(e) => setRouteForm(prev => ({ ...prev, isActive: e.target.checked }))}
              className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
            />
            <label htmlFor="isActive" className="text-sm text-gray-700">
              启用此路线
            </label>
          </div>

          <div className="flex justify-end space-x-3 pt-4">
            <Button variant="outline" onClick={() => setShowCreateRouteModal(false)}>
              取消
            </Button>
            <Button 
              icon={<Save className="w-4 h-4" />}
              onClick={() => handleSaveRoute(false)}
              loading={routeLoading}
            >
              创建路线
            </Button>
          </div>
        </div>
      </Modal>

      {/* 编辑路线模态框 */}
      <Modal
        isOpen={showEditRouteModal}
        onClose={() => setShowEditRouteModal(false)}
        title="编辑路线"
        size="lg"
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">路线名称 *</label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              placeholder="请输入路线名称"
              value={routeForm.name}
              onChange={(e) => setRouteForm(prev => ({ ...prev, name: e.target.value }))}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">起点 *</label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="请输入起点"
                value={routeForm.origin}
                onChange={(e) => setRouteForm(prev => ({ ...prev, origin: e.target.value }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">终点 *</label>
              <input
                type="text"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="请输入终点"
                value={routeForm.destination}
                onChange={(e) => setRouteForm(prev => ({ ...prev, destination: e.target.value }))}
              />
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">距离(公里)</label>
              <input
                type="number"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="距离"
                value={routeForm.distance}
                onChange={(e) => setRouteForm(prev => ({ ...prev, distance: Number(e.target.value) }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">预计时间(小时)</label>
              <input
                type="number"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                placeholder="预计时间"
                value={routeForm.estimatedTime}
                onChange={(e) => setRouteForm(prev => ({ ...prev, estimatedTime: Number(e.target.value) }))}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">交通方式</label>
              <select 
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                value={routeForm.transportMode}
                onChange={(e) => setRouteForm(prev => ({ ...prev, transportMode: e.target.value as any }))}
              >
                <option value="driving">🚗 驾车</option>
                <option value="walking">🚶 步行</option>
                <option value="transit">🚌 公交</option>
              </select>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">适用车型</label>
            <div className="grid grid-cols-2 gap-2">
              {routeVehicleTypeOptions.map(type => (
                <label key={type} className="flex items-center space-x-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={routeForm.vehicleTypes.includes(type)}
                    onChange={(e) => {
                      if (e.target.checked) {
                        setRouteForm(prev => ({ 
                          ...prev, 
                          vehicleTypes: [...prev.vehicleTypes, type] 
                        }));
                      } else {
                        setRouteForm(prev => ({ 
                          ...prev, 
                          vehicleTypes: prev.vehicleTypes.filter(t => t !== type) 
                        }));
                      }
                    }}
                    className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                  />
                  <span className="text-sm text-gray-700">{type}</span>
                </label>
              ))}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">路线描述</label>
            <textarea
              rows={3}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
              placeholder="请输入路线描述（可选）"
              value={routeForm.description}
              onChange={(e) => setRouteForm(prev => ({ ...prev, description: e.target.value }))}
            />
          </div>

          <div className="flex items-center space-x-2">
            <input
              type="checkbox"
              id="isActiveEdit"
              checked={routeForm.isActive}
              onChange={(e) => setRouteForm(prev => ({ ...prev, isActive: e.target.checked }))}
              className="rounded border-gray-300 text-primary-600 focus:ring-primary-500"
            />
            <label htmlFor="isActiveEdit" className="text-sm text-gray-700">
              启用此路线
            </label>
          </div>

          <div className="flex justify-end space-x-3 pt-4">
            <Button variant="outline" onClick={() => setShowEditRouteModal(false)}>
              取消
            </Button>
            <Button 
              icon={<Save className="w-4 h-4" />}
              onClick={() => handleSaveRoute(true)}
              loading={routeLoading}
            >
              保存修改
            </Button>
          </div>
        </div>
      </Modal>

      {/* 删除确认对话框 */}
      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm(prev => ({ ...prev, isOpen: false }))}
        onConfirm={handleConfirmDelete}
        title={`删除${deleteConfirm.type === 'vehicle' ? '车辆' : '路线'}`}
        message={`您确定要删除${deleteConfirm.type === 'vehicle' ? '车辆' : '路线'} "${deleteConfirm.item?.plateNumber || deleteConfirm.item?.name}" 吗？`}
        confirmText="确认删除"
        cancelText="取消"
        type="danger"
        loading={deleteConfirm.loading}
      />
    </div>
  );
};